package com.youzan.cloud.biz.integral.usercase;
import com.alibaba.fastjson.JSONObject;
import com.youzan.cloud.biz.integral.common.CommandHandler;
import com.youzan.cloud.biz.integral.common.UserCommand;
import com.youzan.cloud.biz.integral.common.enums.ActionType;
import com.youzan.cloud.biz.integral.common.enums.PointType;
import com.youzan.cloud.biz.integral.common.enums.SyncStatus;
import com.youzan.cloud.biz.integral.dal.dataobj.PointChange;
import com.youzan.cloud.biz.integral.extension.LinkerExtensionPoints;
import com.youzan.cloud.biz.integral.model.UnFreezePointsCmd;
import com.youzan.cloud.biz.integral.service.LocalPointService;
import com.youzan.cloud.component.retry.annotation.Retry;
import com.youzan.cloud.connect.service.sdk.ConnectServiceResponse;
import com.youzan.cloud.connect.service.sdk.exception.ConnectServiceCallException;
import com.youzan.cloud.connector.component.dto.member.PointDTO;
import com.youzan.cloud.connector.component.dto.member.PointUpdateRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
 * 处理积分解冻数据组装以及连接器调用 并记录日志
 * @author wangyuan
 * @version 1.0
 * @description: 解冻积分usdercase
 * @date 2021/8/19 11:09
 */
@Component
@CommandHandler(responseFor = UnFreezePointsCmd.class)
public class UnFreezePointsUserCase  extends AbstractPointUserCase<UnFreezePointsCmd>{
    private static final Logger log = LoggerFactory.getLogger(UnFreezePointsUserCase.class);
    @Autowired
    private LocalPointService pointService;
    @Override
    public Boolean exec(UserCommand param) throws Exception {
        // force cast
        UnFreezePointsCmd cmd = (UnFreezePointsCmd)param;

        log.info("start exec unfreeze point user case, {}", cmd);
        //todo 查询冻结的积分
        PointChange pointChange = loadFreezePoint(cmd.getBizNo());
        if (null == pointChange) {
            log.warn("No logs matching the conditions are queried bizNO={},pointType={}",pointChange.getBizNo(), PointType.UNFREEZE);
            return false;
        }
        log.info("unfreeze point {}",pointChange);
        cmd.setStatus(UserCommand.ExecStatus.EXECUTING);
        PointDTO pointDTO = new PointDTO.Builder()
                .amount(pointChange.getChangePoints())
                .createdTime(new Date())
                .remark(cmd.getDescription())
                .bizNo(cmd.getBizNo())
                .build();

        PointUpdateRequest request = new PointUpdateRequest.Builder()
//                .appId("")
                .point(pointDTO)
                .mobile(cmd.getMobile())
                //扩展信息
                .extendMap(cmd.getExtParams())
                .build();

        // write serials log
            createLog(cmd,pointChange.getChangePoints());
        // call connector
        ConnectServiceResponse<?> response = syncPointDecreaseToOutSystem(cmd.getBizNo(), request);

        if(null == response || !response.isSuccess()) {
            cmd.setStatus(UserCommand.ExecStatus.FAILED);
            pointService.changeLog(SyncStatus.FAIL.getStatus(),cmd.getBizNo(),PointType.UNFREEZE.getPoint());
         return false;
        } else {
            cmd.setStatus(UserCommand.ExecStatus.DONE);
            pointService.changeLog(SyncStatus.SUCCESS.getStatus(),cmd.getBizNo(),PointType.UNFREEZE.getPoint());
            cmd.setResult(response.getResponseDTO());

        }
         return true;
    }

    /**
     * 加载冻结成功的积分记录
     * @param bizNo
     * @return
     */
    private PointChange loadFreezePoint(String bizNo) {

        return pointService.queryByUnique(bizNo,PointType.FREEZE.getPoint(), SyncStatus.SUCCESS.getStatus());
    }

    @Retry(bizCase = "UnFreezePointsUserCase", uniqKey = "bizNo")
    public ConnectServiceResponse<?>  syncPointDecreaseToOutSystem(String bizNo, PointUpdateRequest request) throws ConnectServiceCallException {

        log.info("SEND_POINT_UNFREEZE_DATA - {}  started", bizNo);
        // call connector
        ConnectServiceResponse<?> response = callLinker(LinkerExtensionPoints.SEND_POINT_UNFREEZE_DATA, request);
        log.info("SEND_POINT_UNFREEZE_DATA - {} finished, result= {}, {}", bizNo, response.isSuccess(), response.getErrMsg());

        return  response;
    }

    private void createLog(UnFreezePointsCmd cmd,Integer amount) {
        PointChange pointChange =  PointChange.builder()
                .pointType(PointType.UNFREEZE.getPoint())
                .actionType(ActionType.INCREASE.getAction())
                .comment(cmd.getDescription())
                .kdtId(String.valueOf(cmd.getNodeId()))
                .yzOpenId(cmd.getYzOpenId())
                .changePoints(amount)
                .changeUsablePoints(amount)
                .bizNo(cmd.getBizNo())
                .createdAt(new Date())
                .id(Long.valueOf(cmd.getId()))
                .build();
        log.info("write  unfreeze point log {}", JSONObject.toJSONString(pointChange));

        pointService.createPointLog(pointChange);
    }
}
